/*
 * @Author: Setsuna
 * @Email: 601890383@qq.com
 * @FilePath: \src\pages\CustomerManage\Customer\component\BrandInfoEditTable\TreeSelectInTable.tsx
 * @Date: 2021-07-09 11:25:54
 * @LastEditTime: 2022-01-12 11:04:28
 */
import React, { useCallback, useState, useEffect } from "react"
import { TreeSelect, Icon } from "antd"
import { http } from "@/lib"
import apis from './../../../../../apis'

const { TreeNode } = TreeSelect

const mapTree = (data: any[]) => {
  return data.map(item => {
    return <TreeNode value={item.code} title={item.name} key={item.code}>
      {mapTree(item?.children ? item?.children : [])}
    </TreeNode>
  })
}

export const TreeSelectInTable = ({ val, setVal, brandCode, defaultDataList,disabled=true }: { val: string, setVal: (valCode, valName, list) => void, brandCode: string, defaultDataList: any[],disabled?:boolean }) => {
  // 是否已获取数据
  let handled = false
  const [loading, setLoading] = useState(false)
  //下拉框数据
  const [dataList, setDataList] = useState([])

  //初始化下拉框数据
  useEffect(() => {
    setDataList(defaultDataList)
  }, [defaultDataList])

  //获取焦点时请求下拉框数据
  const getTreeDataList = useCallback(() => {
    if (brandCode) {
      setLoading(true)
      http.get(apis.getTreeByUser, { params: { organizationCode: brandCode } }).then(res => {
        let data = res?.data?.children || []
        setDataList(data)
      }).finally(() => setLoading(false))
    }
  }, [brandCode])

  return (
    <TreeSelect
      showSearch
      treeNodeFilterProp="title"
      disabled={disabled}
      onFocus={getTreeDataList}
      style={{ width: '100%' }}
      value={val}
      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
      placeholder="请选择管理区域"
      // treeDefaultExpandAll
      onChange={(val, label) => {
        setVal(val, label, dataList)
      }}
      suffixIcon={loading ? <Icon type="loading" /> : null}
    >
      {mapTree(dataList)}
    </TreeSelect>
  )
}